package org.lionsoul.ip2region.lcTest;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class IPAddrText {


    public static void main(String[] args) throws IOException {
        test();
    }

    public static void test() throws IOException {
        // 1、创建 searcher 对象
        String dbPath = "ip2region.xdb";
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
            System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
            return;
        }
        String ip = getIPV4();
        // 2、查询
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
            System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
        } catch (Exception e) {
            System.out.printf("failed to search(%s): %s\n", ip, e);
        } finally {
            // 3、关闭资源
            searcher.close();
        }


        // 备注：并发使用，每个线程需要创建一个独立的 searcher 对象单独使用。
    }

    public static String getIPV4() {
        String ip4 = "1.2.3.4";
        String ipData = HttpUtil.get("http://httpbin.org/ip");
        String ip = JSON.parseObject(ipData).getString("origin");
        if (ip != null) {
            ip4 = ip;
        }
        System.out.println(ip4);
        return ip4;
    }

    public static String getIPV6() {
        String ip4 = "1.2.3.4";
        String ip = HttpUtil.get("https://ipv6.netarm.com");
        if (ip != null && StrUtil.isBlankIfStr(ip)) {
            ip4 = ip;
        }
        ;
        return ip4;
    }
}
